package com.controller.abstractcontroller;

import com.vo.PlayerInstance;
import com.google.flatbuffers.FlatBufferBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;

import javax.annotation.PostConstruct;
import java.nio.ByteBuffer;

/**
 * Created by 石头哥哥 on 8/19/16.
 * PACKAGE_NAME:  controller
 * COMMENT :
 */
public abstract class AbstractController implements IController {

    /**
     * spring 容器初始化 加载并初始化相应控制器处理句柄
     */
    @PostConstruct
    public abstract void PostConstruct();

    /**
     * 基于flatBuffers 结构数据传输
     *
     * @param data   cast subclass of table .
     * @param player game session
     * @throws Exception
     */
    @Override
    public abstract void DispatchFlatBuffer(byte[] data, PlayerInstance player) throws Exception;


    /**
     * @param data
     * @return
     */
    protected ByteBuffer wrap(byte[] data) {
        return ByteBuffer.wrap(data, 4, data.length - 4);//
    }


    /**
     * 构建数据包
     * 包长度:4 字节
     *
     * @param msgID   消息编号
     * @param builder
     * @return
     */
    public static ByteBuf buildBuf(int msgID, FlatBufferBuilder builder) {
        byte[] data = builder.sizedByteArray();
        int length = data.length + 0x8;// packageLength+(msgID+data.length)  == 4+4+dataLength
        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(length, length);
        buffer.setIndex(0, 0x4);//设定writeIndex指针位置    4
        buffer.writeInt(msgID); //编号                4
        buffer.writeBytes(data);
        buffer.setInt(0, buffer.writerIndex() - 0x4); //设置包长度
        // for gc
        builder = null;
        data = null;
        return buffer;
    }

}
